package iuiga.enable;

import iuiga.thirdparty.message.publish.PublishMessage;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration(proxyBeanMethods = false)
@Data
public class ThirdpartyScannerConfigurer implements BeanDefinitionRegistryPostProcessor{

    //自定义资源加载器，要扫描的包
    private static final String basePackage="iuiga.thirdparty";

    /**
     *创建消息中介
     */
    @Bean
    public PublishMessage publishMessage(){
        return new PublishMessage();
    }

    /**
     *要开启异步任务才会加载
     */
    @ConditionalOnProperty(value = "message.async.enable")
    @Bean
    public ThreadPoolExecutor asyncPool(@Value("${message.async.coresize:3}") Integer corePoolSize,
                                        @Value("${message.async.maxsize:15}")Integer maxPoolSize,
                                        @Value("${message.async.keepalive:6}")Integer keepAliveTime){
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1<<12),
                new ThreadPoolExecutor.AbortPolicy());
        return pool;
    }
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        //创建自定义资源解析器对象
        ClassPathResourceScanner mapperScanner = new ClassPathResourceScanner(beanDefinitionRegistry);
        //注册过滤器，目的是检查所有的mapper接口是否是备选组件
        mapperScanner.registerFilters();
        //对该包下的资源进行扫描
        mapperScanner.scan(basePackage);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }
}
